package st.business.tepth.business.taskallocation.returnfactory;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.SupportFragment;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.CommonBean;
import st.business.tepth.business.bean.ReturnFactoryBean;
import st.business.tepth.business.taskallocation.returnfactory.content.ContentDelegate;
import st.business.tepth.config.ItemFields;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.util.utilcode.util.ToastUtils;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-09-02 18:13
 */

public class ReturnFactoryDelegate extends MvpFragment<ReturnFactoryPresenter> implements ReturnFactoryContract.View {
    public static ReturnFactoryDelegate newInstance(int repairId) {
        Bundle bundle = new Bundle();
        bundle.putInt("repairId", repairId);
        ReturnFactoryDelegate delegate = new ReturnFactoryDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R2.id.recycler_view_tab)
    RecyclerView mRecyclerView;
    @BindView(R2.id.layout_container)
    ConstraintLayout mLayoutContainer;
    @BindView(R2.id.tv_tile)
    TextView mTvTitle;
    private int mRepairId;
    private ReturnFactoryAdapter mClassificationAdapter;
    private String phenomenonIds = "";
    private String maintenanceIds = "";
    private DialogLoader mDialogLoader;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mRepairId = bundle.getInt("repairId");
        }
    }

    @Override
    public ReturnFactoryPresenter getPresenter() {
        return new ReturnFactoryPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_return_factory;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mTvTitle.setText("转回主厂");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));
        RecyclerView.ItemAnimator itemAnimator = mRecyclerView.getItemAnimator();
        if (itemAnimator != null) {
            itemAnimator.setChangeDuration(0);
        }
        mRecyclerView.setAdapter(
                mClassificationAdapter = new ReturnFactoryAdapter(R.layout.item_user_classification,
                        null, new
                        OnItemChooseListener<ReturnFactoryBean.Classification>() {
                            @Override
                            public void onChoose(ReturnFactoryBean.Classification classification) {
                                loadContent(classification);
                            }
                        }));
        addTopView(R.layout.view_loading, mLayoutContainer);
        mDialogLoader = new DialogLoader(_mActivity);
        mPresenter.getData(UserManager.getInstance().getToken(), mRepairId);
    }

    @OnClick({R2.id.tv_back})
    public void onBack() {
        pop();
    }

    @Override
    public void showData(ReturnFactoryBean data) {
        removeTopView(mLayoutContainer);
        mClassificationAdapter.setNewData(ReturnFactoryDataConvert
                .convertToClassification(data));
        if (!mClassificationAdapter.getData().isEmpty()) {
            MultipleItemEntity entity = mClassificationAdapter.getItem(0);
            if (entity != null) {
                ReturnFactoryBean.Classification classification =
                        entity.getField(ItemFields.ITEM_OBJ);
                loadContent(classification);
            }
        } else {
            addTopView(R.layout.view_search_empty, mLayoutContainer);
        }
    }

    @Override
    public void returnSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null,
                new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        mDialogLoader.clearDialog();
                        pop();
                    }
                });
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed(msg, msg);
    }

    private void loadContent(ReturnFactoryBean.Classification
                                     classification) {
        SupportFragment contentFragment = findChildFragment(ContentDelegate.class);
        if (contentFragment != null) {
            contentFragment.replaceFragment(ContentDelegate
                    .newInstance(classification), true);
        } else {
            loadRootFragment(R.id.view_content,
                    ContentDelegate
                            .newInstance(classification),
                    false, false);
        }
    }

    @OnClick(R2.id.tv_driver)
    public void onDriverReturn() {
        if (makeData()) {
            mDialogLoader.showProgressDialog(true, "正在提交",
                    "请稍候...");
            mPresenter.returnFactory(UserManager.getInstance().getToken(),
                    mRepairId, phenomenonIds, maintenanceIds, 0);
        } else {
            ToastUtils.showShort("请勾选作业项");
        }

    }

    @OnClick(R2.id.tv_help)
    public void onHelpReturn() {
        if (makeData()) {
            mDialogLoader.showProgressDialog(true, "正在提交",
                    "请稍候...");
            mPresenter.returnFactory(UserManager.getInstance().getToken(),
                    mRepairId, phenomenonIds, maintenanceIds, 1);
        } else {
            ToastUtils.showShort("请勾选作业项");
        }

    }

    private boolean makeData() {
        if (mClassificationAdapter != null) {
            List<MultipleItemEntity> entityList = mClassificationAdapter.getData();
            for (MultipleItemEntity entity : entityList) {
                ReturnFactoryBean.Classification classification
                        = entity.getField(ItemFields.ITEM_OBJ);
                if (classification != null) {
                    List<ReturnFactoryBean.ClassCategory> classCategories
                            = classification.getCategoryList();
                    if (classCategories != null) {
                        for (ReturnFactoryBean.ClassCategory classCategory
                                : classCategories) {
                            List<CommonBean> maintainList
                                    = classCategory.getMaintenanceList();
                            if (maintainList != null) {
                                for (CommonBean commonBean : maintainList) {
                                    if (commonBean.isSelected()) {
                                        maintenanceIds += commonBean.getId() + ",";
                                    }
                                }
                            }
                        }
                    }
                    List<CommonBean> repairList = classification.getRepairPhenomenonList();
                    if (repairList != null) {
                        for (CommonBean commonBean : repairList) {
                            if (commonBean.isSelected()) {
                                phenomenonIds += commonBean.getId() + ",";
                            }
                        }
                    }
                }
            }
            if (!maintenanceIds.isEmpty()) {
                maintenanceIds = maintenanceIds.substring(0, maintenanceIds.length() - 1);
            }
            if (!phenomenonIds.isEmpty()) {
                phenomenonIds = phenomenonIds.substring(0, phenomenonIds.length() - 1);
            }
            if (maintenanceIds.isEmpty() && phenomenonIds.isEmpty()) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}